package code.google.model.local;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import code.google.model.groove.util.SongInfo;
import code.google.model.util.interfaces.ISong;

public class LocalClient {
	
	
	private List<ISong> songs = new ArrayList<ISong>();
	
	private String[] projection = {
			MediaStore.Audio.Media.ALBUM,
			MediaStore.Audio.Media.ARTIST,
			MediaStore.Audio.Media.TITLE,
			MediaStore.Audio.Media.DATA
			};
	
	private String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
			
	
	public LocalClient(){
		
	}

	public void scanStorage(Activity context) {
		
		Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
		
		Cursor cursor = context.getContentResolver().query(uri, projection, selection, null, null);
		if (cursor == null) {
		    // query failed, handle error.
		} else if (!cursor.moveToFirst()) {
		    // no media on the device
		} else {
			
			songs = new ArrayList<ISong>();
			
			int albumCol = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ALBUM);
		    int artistCol = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
		    int titleCol = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
		    int dataCol = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA);
		    
		    do {
		    		
	    		ISong song = new LocalSong();
	    		
	    		song.setAlbumName(cursor.getString(albumCol));
	    		song.setArtistName(cursor.getString(artistCol));
	    		song.setSongName(cursor.getString(titleCol));
	    		song.setFilePath(cursor.getString(dataCol));
	    		
	    		songs.add(song);
		    } while (cursor.moveToNext());
		}	
		
		cursor.close();
		
		
	}
	
	
	public File getSongFile(SongInfo info) {
		return new File(info.getFilePath());
	}
	


	public List<ISong> doSearch(String query) {
		List<ISong> result = new ArrayList<ISong>();
		for (ISong song : songs) {
			if(matchesQuery(song, query))
				result.add(song);
		}
		
		return result;
	}
	
	private boolean matchesQuery(ISong song, String query){
		Locale l = Locale.getDefault();
		String temp = query.toUpperCase(l);
		if(song.getAlbumName().toUpperCase(l).contains(temp))
			return true;
		if(song.getArtistName().toUpperCase(l).contains(temp))
			return true;
		if(song.getSongName().toUpperCase(l).contains(temp))
			return true;
		return false;
	}

}
